const express = require("express")
const router = express.Router()
const sqlFn = require("../mysql")
const CrpytoJs = require("crypto-js")
const jwt = require("jsonwebtoken")
const {jwtSecret} = require("../config")
/**
 * @swagger
 * /login:
 *   post:
 *     summary: 用户登录
 *     description: 用户使用账号和加密后的密码进行登录，成功后返回 JWT 令牌
 *     tags:
 *       - 用户认证
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               account:
 *                 type: string
 *                 description: 用户账号
 *                 example: "admin"
 *               password:
 *                 type: string
 *                 description: 加密后的用户密码
 *                 example: "U2FsdGVkX19vcmJ3dB3r..."
 *     responses:
 *       200:
 *         description: 登录成功，返回 JWT 令牌
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 msg:
 *                   type: string
 *                   example: "登录成功"
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 token:
 *                   type: string
 *                   example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
 *       400:
 *         description: 登录失败，账号或密码错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 400
 *                 msg:
 *                   type: string
 *                   example: "账号或密码错误"
 */
router.post("", function (req, res, next) {
    const sql = "select*from user where `account`=? and `password`=?"
    const password = CrpytoJs.AES.decrypt(req.body.password, "12345678").toString(CrpytoJs.enc.Utf8)
    sqlFn(sql, [req.body.account, password], function (err, data) {
        if (err) {
            next(err)
            return
        }
        if (data && data.length) {
            const token = jwt.sign({account: data[0].account}, jwtSecret)
            res.send({code: 200, msg: "登录成功", success: true, token})
        } else {
            res.send({code: 400, msg: "账号或密码错误"})
        }
    })
})
module.exports = router